package com.hjc.sort;

import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] data = new int[]{
                3, 14, 4, 7, 10, 8, 9, 2, 1, 16,
        };
        HeapSort.sort(data);
        System.out.println(Arrays.toString(data));
    }

    public static void sort(int[] data) {
        buildMaxHeap(data, data.length);
        for (int i = data.length - 1; i >= 1; i--) {
            exchangeValue(data, 0, i);
            buildMaxHeap(data, i);
        }
    }

    private static int leftIndex(int i) {
        return 2 * i + 1;
    }

    private static int rightIndex(int i) {
        return 2 * (i + 1);
    }

    private static int parentIndex(int i) {
        return (i - 1) / 2;
    }

    private static void exchangeValue(int[] data, int i, int j) {
        int tmp = data[i];
        data[i] = data[j];
        data[j] = tmp;
    }

    private static void fixMaxHeap(int[] data, int i, int heapSize) {
        int left = leftIndex(i);
        int right = rightIndex(i);

        showTree(data, heapSize);
        //left > parent
        if (left < heapSize && data[i] < data[left]) {
            if (right < heapSize && data[left] < data[right]) {
                exchangeValue(data, i, right);
            } else {
                exchangeValue(data, i, left);
            }
        }
        //left > parent
        else if (right < heapSize && data[i] < data[right]) {
            exchangeValue(data, i, right);
        }
        //else return
        else if (left >= heapSize || right >= heapSize) {
            return;
        }

        //fix left
        fixMaxHeap(data, left, heapSize);
        //fix right
        fixMaxHeap(data, right, heapSize);
    }

    public static void buildMaxHeap(int[] data, int heapSize) {
        fixMaxHeap(data, 0, heapSize);
    }

    public static void showTree(int[] data, int length) {
        int height = 1;
        while (length >= Math.pow(2, height)) {
            height++;
        }
        StringBuffer[] stringBuffers = new StringBuffer[height];
        for (int i = 0; i < height; i++) {
            stringBuffers[i] = new StringBuffer();
            int heightFirstOne = (int) (Math.pow(2, i) - 1);
            int heightLength = (int) Math.pow(2, i );
            for (int j = heightFirstOne; (j < heightFirstOne + heightLength) && (j < length); j++) {
                stringBuffers[i].append(data[j]).append("\t");
            }
        }
        System.out.println("=====================================");
        Arrays.stream(stringBuffers).forEach(System.out::println);
        System.out.println("=====================================");
        System.out.println();
    }

}
